<?php

namespace App\Http\Controllers;

use App\Exceptions\InvalidRequestException;
use App\Jobs\CloseOrder;
use App\Models\Order;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrdersController extends Controller
{

    public function store(\App\Http\Requests\OrderRequest $request)
    {
        $user = $request->user();

        $order = DB::transaction(function () use ($user, $request) {
            $address = $user->addresses()->find($request->address_id);
            $address->update([
                'last_used_at' => now(),
            ]);
            $order = new Order([
                'address' => [
                    'address_id' => $address->full_address,
                    'zip' => $address->zip,
                    'contact_name' => $address->contact_name,
                    'contact_phone' => $address->contact_phone,
                ],
                'remark' => $request->mark,
                'total_amount' => 0,
            ]);
            $order->user()->associate($user);
            $order->save();

            $totalAmount = 0;

            $items = $request->items;

            foreach ($items as $data) {
                $sku = \App\Models\ProductSku::find($data['sku_id']);
                $item = $order->orderItems()->make([
                    'amount' => $data['amount'],
                    'price' => $sku->price,
                ]);
                $item->product()->associate($sku->product_id);
                $item->productSku()->associate($sku);
                $item->save();
                $totalAmount += $sku->price * $data['amount'];
                if ($sku->decreaseStock($data['amount']) <= 0) {
                    throw new InvalidRequestException('该商品库存不足');
                }
            }
            $order->update(
                ['total_amount' => $totalAmount,]
            );

            $skuIds = collect($items)->pluck('sku_id');
            $user->cartItems()->whereIn('product_sku_id', $skuIds)->delete();
            return $order;
        });
        $this->dispatch(new CloseOrder($order, config('app.order_ttl')));
        return $order;
    }

    public function index(Request $request)
    {
        $orders = Order::query()
            ->with(['orderItems.product', 'orderItems.productSku'])
            ->where('user_id', $request->user()->id)
            ->orderByDesc('created_at')
            ->paginate();
        return view('orders.index', compact('orders'));
    }

    public function show(Order $order,Request $request)
    {
        $this->authorize('own', $order);
        return view('orders.show', ['order' => $order->load(['orderItems.productSku', 'orderItems.product'])]);
    }
}
